const express = require('express');
const router = express.Router();
const fs = require('fs');
const cookieParser = require('cookie-parser');

const PageModel = require('../models/page');

router.use(cookieParser())
const {
    pinyin
} = require('pinyin-pro');
const async = require('async');
const {
    Domain
} = require('domain');

//提交文章  标题title  内容content  分类classify
router.post('/submitPage', function (req, res) {
    var tasks = {
        getParmas: function (cb) {
            var {
                title,
                content,
                classify
            } = req.body;
            classify = classify.toLowerCase()
            var pinyinResult = pinyin(title, {
                toneType: 'none'
            })
            cb(null, {
                classify,
                pinyinResult,
                content,
                title
            })
        },
        isDir: ["getParmas", function (value1, cb) {
            var {
                classify
            } = value1.getParmas
            fs.readdir('./source', function (err, files) {
                if (err) {
                    cb("读取文件夹失败")
                } else {
                    if (files.includes(classify)) {
                        cb(null)
                    } else {
                        fs.mkdir(`./source/${classify}`, function (err) {
                            if (err) {
                                cb("文件夹创建失败")
                            } else {
                                cb(null)
                            }
                        })
                    }
                }
            })
        }],
        setHtml: ["isDir", function (value2, cb) {
            var {
                title,
                classify,
                content
            } = value2.getParmas
            var realPath = `./source/${classify}/${title}.html`;
            console.log(realPath)
            fs.readFile('./public/templete.html', 'utf-8', function (err, data) {
                if (err) {
                    cb('模版读取失败')
                } else {
                    data = data.replace('$title', title).replace('$title', title).replace('$content', content)
                    fs.writeFile(realPath, data, function (err) {
                        if (err) {
                            cb("文件写入失败")
                        } else {
                            cb(null)
                        }
                    })
                }
            })
        }],
        setMongoose: ["setHtml", function (value3, cb) {
            var {
                title,
                classify,
                pinyinResult
            } = value3.getParmas
            var now = new Date();
            var day = now.getDate(); //日期  21
            var month = now.getMonth() + 1; // 11
            var year = now.getFullYear(); //2021
            const page = new PageModel({
                title,
                classify: classify,
                count: 0,
                time: `${year}.${month}.${day}`,
                pinyin: pinyinResult
            })
            page.save(() => {
                cb(null)
            })
        }]
    }
    async.auto(tasks, (err, resultEnd) => {
        if (err) {
            console.log(err)
        } else {
            res.send('文件生成成功')
        }
    })
})
//获取首页导航栏数据
router.get('/getNav', function (req, res) {
    fs.readdir('./source', function (err, files) {
        if (err) {
            console.log('文件夹获取失败')
        } else {
            res.send(files)
        }
    })
})
//获取主题下边所有的文章
router.post('/getClassPage', function (req, res) {
    var {
        classify
    } = req.body;
    classify = classify.slice(1);
    PageModel.find({
        classify: classify
    }).then((result) => {
        res.send(result)
    })
})
//获取热门的文章
router.get('/hot', function (req, res) {
    //1.根据点击量搜寻相应的热门文章
    //2.把热门列表发送到前端去
    PageModel.find({}).sort({
        'count': -1
    }).limit(5).then((result) => {
        res.send(result)
    }).catch((err) => {
        res.send("查找失败")
    })
})
//获取文章内容
router.post('/pageDetail', function (req, res) {
    const {
        title,
        classify
    } = req.body;
    var realPath = `./source/${classify}/${title}.html`;
    fs.readFile(realPath, "utf-8", function (err, data) {
        if (err) {
            console.log('文章读取失败')
        } else {
            PageModel.find({
                title: title,
                classify: classify
            }).then((datas) => {
                PageModel.updateOne({
                    title: title,
                    classify: classify
                }, {
                    count: ++datas[0].count
                }).then(() => {
                    res.send(data)
                })
            })
        }
    })
})
router.post('/search', function (req, res) {
    var tasks = {
        getParams: function (cb) {
            var {
                wd
            } = req.body;
            wd = pinyin(wd, {
                toneType: 'none'
            })
            const reg = new RegExp(`${wd}`);
            cb(null, {
                reg
            })
        },
        findSearch: ["getParams", function (value, cb) {
            var {
                reg
            } = value.getParams;
            PageModel.find({
                pinyin: reg
            }).then((result) => {
                cb(null, {
                    result
                })
            })
        }]
    }
    async.auto(tasks, (err, resultEnd) => {
        if (err) {
            console.log(err)
        } else {
            var {
                result
            } = resultEnd.findSearch
            res.send(result)
        }
    })
})
router.post('/delete', function (req, res) {
    const {
        classify,
        title
    } = req.body
    var path = `./source/${classify}/${title}.html`
    fs.unlink(path, function (err) {
        if (err) {
            console.log(err)
            return false
        }
        PageModel.deleteOne({
            classify,
            title
        }).then((result) => {
            console.log('数据库删成功')
        }).catch((err) => {
            console.log('数据库删失败');
        })
        console.log('文件删除成功');
        //判断文件夹要不要删除
        fs.rmdir(`./source/${classify}`, (err) => {
            if (err) {
                console.log('err');
                return false
            }

        })
        //自动跳出来
    })
})



module.exports = router;